<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ProblemApi } from '@/api/ProblemApi.ts'
import type { AddRequest } from '@/api/Problem.ts'
import { message } from 'ant-design-vue'
import {
  ArrowLeftOutlined,
  PlusOutlined,
  DeleteOutlined,
  CheckOutlined
} from '@ant-design/icons-vue'
import MdEditor from '@/components/MdEditor.vue'
import { useUserInfoStore } from '@/stores/UserInfo'

const router = useRouter()
const userInfoStore = useUserInfoStore()

const loading = ref(false)
const formRef = ref()

const formData = reactive<AddRequest>({
  title: '',
  description: '',
  difficulty: 0,
  judgeConfig: {
    timeLimit: 1000,
    memoryLimit: 128
  },
  inputDescription: '',
  outputDescription: '',
  sampleInput: '',
  sampleOutput: '',
  hint: '',
  judgeCases: [
    { input: '', output: '' }
  ],
  createdUserId: userInfoStore.currentUser?.id || ''
})

const rules = {
  title: [
    { required: true, message: '请输入题目标题', trigger: 'blur' },
    { min: 1, max: 255, message: '标题长度应在1-255字符之间', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入题目描述', trigger: 'blur' },
    { max: 1024, message: '题目描述长度不能超过1024字符', trigger: 'blur' }
  ],
  difficulty: [
    { required: true, message: '请选择难度', trigger: 'change' },
    { type: 'number', min: 0, max: 2, message: '难度参数错误', trigger: 'change' }
  ],
  inputDescription: [
    { required: true, message: '请输入输入描述', trigger: 'blur' },
    { max: 1024, message: '输入描述长度不能超过1024字符', trigger: 'blur' }
  ],
  outputDescription: [
    { required: true, message: '请输入输出描述', trigger: 'blur' },
    { max: 1024, message: '输出描述长度不能超过1024字符', trigger: 'blur' }
  ],
  sampleInput: [
    { max: 1024, message: '样例输入长度不能超过1024字符', trigger: 'blur' }
  ],
  sampleOutput: [
    { max: 1024, message: '样例输出长度不能超过1024字符', trigger: 'blur' }
  ],
  hint: [
    { max: 1024, message: '提示长度不能超过1024字符', trigger: 'blur' }
  ]
}

const difficultyOptions = [
  { value: 0, label: '简单', color: 'green' },
  { value: 1, label: '中等', color: 'orange' },
  { value: 2, label: '困难', color: 'red' }
]

const addJudgeCase = () => {
  formData.judgeCases.push({ input: '', output: '' })
}

const removeJudgeCase = (index: number) => {
  if (formData.judgeCases.length > 1) {
    formData.judgeCases.splice(index, 1)
  } else {
    message.warning('至少保留一个测试用例')
  }
}

const onSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

    if (!userInfoStore.currentUser || !userInfoStore.currentUser.id) {
      message.error('用户未登录，请先登录')
      loading.value = false
      return
    }

    formData.createdUserId = userInfoStore.currentUser.id

    // 验证判题配置
    if (!formData.judgeConfig) {
      message.error('判题配置不能为空')
      loading.value = false
      return
    }

    if (!formData.judgeConfig.timeLimit || formData.judgeConfig.timeLimit <= 0) {
      message.error('时间限制必须大于0')
      loading.value = false
      return
    }

    if (!formData.judgeConfig.memoryLimit || formData.judgeConfig.memoryLimit <= 0) {
      message.error('内存限制必须大于0')
      loading.value = false
      return
    }

    // 验证判题用例
    if (!formData.judgeCases || formData.judgeCases.length === 0) {
      message.error('判题用例不能为空')
      loading.value = false
      return
    }

    // 验证每个测试用例的长度
    for (let i = 0; i < formData.judgeCases.length; i++) {
      const judgeCase = formData.judgeCases[i]
      if (judgeCase.input && judgeCase.input.length > 1024) {
        message.error(`测试用例${i + 1}的输入长度不能超过1024字符`)
        loading.value = false
        return
      }
      if (judgeCase.output && judgeCase.output.length > 1024) {
        message.error(`测试用例${i + 1}的输出长度不能超过1024字符`)
        loading.value = false
        return
      }
    }

    if (formData.judgeCases.length === 0) {
      message.error('请至少添加一个有效的测试用例')
      loading.value = false
      return
    }

    const submitData = {
      ...formData,
    }

    console.log('提交数据:', submitData)

    await ProblemApi.add(submitData)
    message.success('题目添加成功')
    router.push('/admin/problem')
  } catch (error) {
    console.error('添加题目失败:', error)
    message.error('添加题目失败')
  } finally {
    loading.value = false
  }
}

const onCancel = () => {
  router.push('/admin/problem')
}

const resetForm = () => {
  formRef.value?.resetFields()
  // 重置 judgeConfig
  formData.judgeConfig = {
    timeLimit: 1000,
    memoryLimit: 128
  }
  // 重置判题用例
  formData.judgeCases = [{ input: '', output: '' }]
}

// MdEditor 变化处理函数
const onDescriptionChange = (value: string) => {
  formData.description = value
}

const onInputDescriptionChange = (value: string) => {
  formData.inputDescription = value
}

const onOutputDescriptionChange = (value: string) => {
  formData.outputDescription = value
}

const onHintChange = (value: string) => {
  formData.hint = value
}
</script>

<template>
  <div class="w-full">
    <a-card
      class="w-full rounded-lg shadow-sm"
      :bodyStyle="{ padding: '24px' }"
    >
      <template #title>
        <div class="flex items-center gap-3">
          <a-button type="text" @click="onCancel" class="p-0 h-auto">
            <ArrowLeftOutlined class="text-lg" />
          </a-button>
          <span class="text-lg font-semibold text-gray-800">新增题目</span>
        </div>
      </template>

      <div class="overflow-y-auto pr-2" style="max-height: calc(100vh - 250px)">
        <a-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          layout="vertical"
        >
        <!-- 基本信息部分 -->
        <a-divider orientation="left" class="font-bold text-blue-600">基本信息</a-divider>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="题目标题" name="title" required>
              <a-input
                v-model:value="formData.title"
                placeholder="请输入题目标题"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="难度等级" name="difficulty" required>
              <a-radio-group v-model:value="formData.difficulty">
                <a-radio
                  v-for="option in difficultyOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  <a-tag :color="option.color">{{ option.label }}</a-tag>
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 题目描述部分 -->
        <a-divider orientation="left" class="font-bold text-blue-600">题目描述</a-divider>
        <a-form-item label="题目内容" name="description" required>
          <MdEditor
            :value="formData.description"
            :handle-change="onDescriptionChange"
          />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="输入描述" name="inputDescription" required>
              <MdEditor
                :value="formData.inputDescription"
                :handle-change="onInputDescriptionChange"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="输出描述" name="outputDescription" required>
              <MdEditor
                :value="formData.outputDescription"
                :handle-change="onOutputDescriptionChange"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 样例 -->
        <a-divider orientation="left" class="font-bold text-blue-600">样例</a-divider>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="样例输入（可选）" name="sampleInput">
              <a-textarea
                v-model:value="formData.sampleInput"
                placeholder="请输入样例输入"
                :auto-size="{ minRows: 3, maxRows: 6 }"
                :maxlength="1024"
                show-count
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="样例输出（可选）" name="sampleOutput">
              <a-textarea
                v-model:value="formData.sampleOutput"
                placeholder="请输入样例输出"
                :auto-size="{ minRows: 3, maxRows: 6 }"
                :maxlength="1024"
                show-count
              />
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 判题配置部分 -->
        <a-divider orientation="left" class="font-bold text-blue-600">判题配置</a-divider>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="时间限制 (ms)" required>
              <a-input-number
                v-model:value="formData.judgeConfig.timeLimit"
                :min="1"
                :max="10000"
                placeholder="请输入时间限制"
                class="w-full"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="内存限制 (MB)" required>
              <a-input-number
                v-model:value="formData.judgeConfig.memoryLimit"
                :min="1"
                :max="1024"
                placeholder="请输入内存限制"
                class="w-full"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 测试用例部分 -->
        <a-divider orientation="left" class="font-bold text-blue-600">测试用例</a-divider>
        <div class="mb-6">
          <a-collapse :default-active-key="['0']">
            <a-collapse-panel
              v-for="(judgeCase, index) in formData.judgeCases"
              :key="index"
              :header="`测试用例 ${index + 1}`"
            >
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item
                    :name="['judgeCases', index, 'input']"
                    label="输入样例"
                  >
                    <a-textarea
                      v-model:value="judgeCase.input"
                      :auto-size="{ minRows: 3, maxRows: 6 }"
                      placeholder="请输入测试输入样例"
                      :maxlength="1024"
                      show-count
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    :name="['judgeCases', index, 'output']"
                    label="输出样例"
                  >
                    <a-textarea
                      v-model:value="judgeCase.output"
                      :auto-size="{ minRows: 3, maxRows: 6 }"
                      placeholder="请输入测试输出样例"
                      :maxlength="1024"
                      show-count
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <div class="flex justify-end mt-2">
                <a-button danger @click="removeJudgeCase(index)">
                  <template #icon>
                    <DeleteOutlined />
                  </template>
                  删除此用例
                </a-button>
              </div>
            </a-collapse-panel>
          </a-collapse>

          <div class="flex justify-center mt-4">
            <a-button type="dashed" @click="addJudgeCase" class="w-48">
              <template #icon>
                <PlusOutlined />
              </template>
              新增测试样例
            </a-button>
          </div>
        </div>

        <!-- 提示 -->
        <a-divider orientation="left" class="font-bold text-blue-600">提示</a-divider>
        <a-form-item label="提示信息（可选）" name="hint">
          <MdEditor
            :value="formData.hint || ''"
            :handle-change="onHintChange"
          />
        </a-form-item>
        </a-form>
      </div>

      <!-- 底部按钮区域 -->
      <div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200">
        <a-button size="large" @click="resetForm" class="px-8">
          重置
        </a-button>
        <a-button
          type="primary"
          size="large"
          @click="onSubmit"
          :loading="loading"
          class="px-8"
        >
          <template #icon>
            <CheckOutlined />
          </template>
          创建题目
        </a-button>
      </div>
    </a-card>
  </div>
</template>

<style scoped>
:deep(.ant-divider-inner-text) {
  font-weight: 600;
  color: #1890ff;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
}

:deep(.ant-collapse-header) {
  font-weight: 500;
}

:deep(.ant-input-number) {
  width: 100%;
}

/* 自定义滚动条样式 */
.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>
